export default function (Vue){
  Vue.directive("drag",{
    inserted(el, binding,vnode) {
      el.style.width = binding.value.width + "px";
      el.style.height = binding.value.height + "px";
      el.style.top = binding.value.positionY + "px";
      el.style.left = binding.value.positionX + "px";
      el.style.background = `url('${binding.value.img}')`;
      el.style.objectFit = "scale-down";
      el.style.backgroundSize = "100% 100%";
      el.style.position = "absolute";
      el.onmousedown = (ev) => {
        let root = document.querySelector("#canvas");
        // 事件对象
        ev = ev || event;
        // 存值
        var disX = ev.pageX - el.offsetLeft;
        var disY = ev.pageY - el.offsetTop;
        var maxWidth = parseInt(root.clientWidth) - el.clientWidth;
        var maxHeight = parseInt(root.clientHeight) - el.clientHeight;
        // 再页面上移动
        document.onmousemove = (ev) => {
          ev = ev || event;
          // 移动过后的值
          var x = ev.pageX - disX;
          var y = ev.pageY - disY;
          // 判断边界值
          // 左边界
          if (x <= 0) {
            x = 0;
          }
          // 右边界
          if (x >= maxWidth) {
            x = maxWidth;
          }
          // 上边界
          if (y <= 0) {
            y = 0;
          }
          // 下边界
          if (y >= maxHeight) {
            y = maxHeight;
          }
          let newdata = {...binding.value} 
          newdata.positionX = Number(x);
          newdata.positionY = Number(y);
          binding.value = newdata
          el.style.left = x + "px";
          el.style.top = y + "px";
          let index = vnode.context.dataList.findIndex(item=>item.id == binding.value.id)
          vnode.context.dataList[index].positionX = x
          vnode.context.dataList[index].positionY = y
        };

        // 鼠标离开把move事件清除
        document.onmouseup = function () {
          document.onmousemove = null;
          document.onmouseup = null;
        };
      };
    },
    bind(){
      
    },
    update(){},
    unbind(){}
  })
  Vue.directive("bgImg",{
    inserted(e, binding){
      e.style.background = `url('${binding.value}')`
    }
  })
}